<?php
/**
 * 工具脚本
 * @version 1.0.0
 */
$rootPath = './';
$structureFile = './_0-structure.sql';
$menuFile = './_0-menu.php';

buildStructureFile($rootPath, $structureFile);
buildMenuFile($rootPath, $menuFile);

/**
 * 遍历文件，抽取 SQL 命令到单独文件。
 * @version 1.0.0
 */
function buildStructureFile(string $rootPath, string $outputFile): void
{
    file_put_contents($outputFile, '');
    $prefix = 'es_';
    $barstr = str_repeat('+', 20);
    $ln = PHP_EOL;
    $fsi = new FilesystemIterator($rootPath);
    foreach ($fsi as $file) {
        $filename = $file->getFilename();
        if (str_starts_with($filename, '_') || !str_ends_with($filename, '模块.md')) {
            echo '[skip] ', $filename, PHP_EOL;
            continue;
        }
        $content = file_get_contents($rootPath . $filename);
        $pos = strpos($content, '```sql');
        if (!$pos) {
            echo '[skip] ', $filename, PHP_EOL;
            continue;
        }
        $content = trim(substr($content, $pos + 6));
        $pos = strpos($content, '```');
        $content = trim(substr($content, 0, $pos));
        $content = preg_replace('/(EXISTS|TABLE)\s+`*([a-z|0-9|_]+)`*/', "$1 `{$prefix}$2`", $content);
        $title = str_replace('.md', '', $filename);
        $content = "{$ln}-- {$barstr} {$title} {$barstr}{$ln}{$ln}{$content}{$ln}";
        file_put_contents($outputFile, $content, FILE_APPEND);
        echo '[ok] ', $filename, PHP_EOL;
    }
    unset($fsi);
    echo 'success';
}

/**
 * 遍历文件，抽取SQL命令生成菜单树形数据。
 * @version 1.0.0
 */
function buildMenuFile(string $rootPath, string $outputFile): void
{
    file_put_contents($outputFile, '');
    $prefix = 'es_';
    $barstr = str_repeat('+', 20);
    $ln = PHP_EOL;
    $fsi = new FilesystemIterator($rootPath);
    $data = [
        '运营数据' => [
            'Index' => '运营概览',
        ],
    ];
    foreach ($fsi as $file) {
        $filename = $file->getFilename();
        if (str_starts_with($filename, '_') || !str_ends_with($filename, '模块.md')) {
            echo '[skip] ', $filename, PHP_EOL;
            continue;
        }
        $content = file_get_contents($rootPath . $filename);
        $pos = strpos($content, '```sql');
        if (!$pos) {
            echo '[skip] ', $filename, PHP_EOL;
            continue;
        }
        $content = trim(substr($content, $pos + 6));
        $pos = strpos($content, '```');
        $content = trim(substr($content, 0, $pos));
        // 提取所有数据表名称
        $matchesOfTables = [];
        
        preg_match_all('/(EXISTS|TABLE)\s+`*([a-z|0-9|_]+)`*\s*\(/', $content, $matchesOfTables);
        if (!$matchesOfTables) {
            continue;
        }
        // 提取数据表注释
        $matchesOfComments = [];
        preg_match_all("/COMMENT='([^?]+)\?module=([^']+)'/", $content, $matchesOfComments);
        foreach ($matchesOfTables[2] as $i => $table) {
            $title = $matchesOfComments[1][$i] ?? '';
            $module = $matchesOfComments[2][$i] ?? '';
            if (!isset($data[$module])) {
                $data[$module] = [];
            }

            $pascalCaseName = str_replace('_', '', ucwords($table, '_'));
            // $camelCaseName = lcfirst($pascalCaseName);
            // $kebabCaseName = str_replace('_', '-', $table);
            if (!isset($data[$module][$pascalCaseName])) {
                $data[$module][$pascalCaseName] = $title;
            }
            $lines[] = "";
            // echo '[ok] ', $table, ' ', $title, ' ', $module, PHP_EOL;
        }
    }
    unset($fsi);
    $lines = [];
    $lines[] = '<?php';
    $lines[] = '';
    $lines[] = '/**';
    $lines[] = ' * 菜单数据';
    $lines[] = ' */';
    $lines[] = 'return [';
    $actionsOfDefault = [
        'option' => '显示资源选项', 'index' => '显示资源列表', 'read' => '显示指定的资源', 'save' => '保存新建的资源',
        'update' => '保存更新的资源', 'delete' => '删除指定资源',
    ];
    $actionsOfIndex = ['main' => '显示统计资源', 'menu' => '显示用户菜单资源',];
    foreach ($data as $module => $controllers) {
        $lines[] = "\t['title' => '{$module}', 'children' => [";
        foreach ($controllers as $controller => $title) {
            $lines[] = "\t\t['title' => '{$title}', 'controller' => '{$controller}', 'children' => [";
            $actions = $actionsOfDefault;
            if ($controller == 'Index') {
                $actions = $actionsOfIndex;
            } 
            foreach ($actions as $action => $actionTitle) {
                $lines[] = "\t\t\t['title' => '{$actionTitle}', 'action' => '{$action}'],";
            }
            $lines[] = "\t\t]],";
        }
        $lines[] = "\t]],";
    }
    $lines[] = '];';
    file_put_contents($outputFile, implode(PHP_EOL, $lines));
    echo 'success';
}
